#include "ThreadSafeZYFPFactory.h"
#include <QThread>
#include <QMap>
#include <QMutex>

static QMap<Qt::HANDLE, zyfp_handle*> _tmap;
typedef QMap<Qt::HANDLE, zyfp_handle*>::iterator _TmapIter;
static QMutex	_tmutex;
#define RES_FILE_PATH "../res.zyfp"
#define RES_FILE_PASSWD "marry has a little lamb"

zyfp_handle*ThreadSafeZYFPFactory::giveMeHandle()
{
	Qt::HANDLE key = QThread::currentThreadId();
	_TmapIter it = _tmap.find(key);
	zyfp_handle* ret = NULL;
	if (it == _tmap.end()) {
		ret = zyfp_init(RES_FILE_PATH, RES_FILE_PASSWD, ZYFP_O_READ);
		if (ret) {
			_tmutex.lock();
			_tmap.insert(key, ret);
			_tmutex.unlock();
		}
	} else {
		ret = it.value();
	}
	return ret;
}

void ThreadSafeZYFPFactory::end()
{
	zyfp_handle* ph;
	for (_TmapIter it = _tmap.begin(); it != _tmap.end(); ++it){
		ph = it.value();
		zyfp_end(ph);
	}
	_tmap.clear();
}
